<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
</head>
<body>
    <a href="https://blog.csdn.net/weixin_33759269/article/details/89064157">有趣的6种图片灰度转换算法</a>
    <form enctype="multipart/form-data">
        <div class="upload">上传图片</div>
        <input type="file" onchange="html5Reader()" />
        <p>原始图片:</p>
        <p>
            <img id="preview" alt="" />
        </p>
        <p>处理成灰度图之后:</p>
        <p>
            <img id="grayImg" alt="" />
        </p>
    </form>
    <canvas id="grayImage"></canvas>
    <script>
        function html5Reader() {
            var file = event.target.files[0]
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                var pic = document.getElementById("preview");
                pic.onload = function() {
                    document.getElementById("grayImg").src = gray(this)
                }
                pic.src = this.result;
            }
        }
        function gray(imgObj) {
            var canvas = document.createElement('canvas');
            var canvasContext = canvas.getContext('2d');
            var imgW = imgObj.width;
            var imgH = imgObj.height;
            canvas.width = imgW;
            canvas.height = imgH;
            canvasContext.drawImage(imgObj, 0, 0);
            var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);
            for (var y = 0; y < imgPixels.height; y++) {
                for (var x = 0; x < imgPixels.width; x++) {
                    var i = (y * 4) * imgPixels.width + x * 4;
                    var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                    imgPixels.data[i] = avg;
                    imgPixels.data[i + 1] = avg;
                    imgPixels.data[i + 2] = avg;
                }
            }
            canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
            return canvas.toDataURL();
        }
    </script>
</body>
</html>